#include <my_head.h>

int main()
{
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, -1, "socket");

    struct sockaddr_in serveraddr;
    serveraddr.sin_addr.s_addr = inet_addr("192.168.108.128");
    serveraddr.sin_port = htons(8000);
    serveraddr.sin_family = AF_INET;

    int ret = connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "bind");
    printf("conncet sucess\n");

    fd_set readset;
    FD_ZERO(&readset);
    int maxfd = (clientfd > STDIN_FILENO) ? clientfd : STDIN_FILENO;
    char buf[1024] = {0};
    while (1)
    {
        FD_ZERO(&readset);
        FD_SET(clientfd, &readset);
        FD_SET(STDIN_FILENO, &readset);
        select(maxfd + 1, &readset, NULL, NULL, NULL);
        if (FD_ISSET(STDIN_FILENO, &readset))
        {
            // 监听到了标准输入
            memset(buf, 0, sizeof(buf));
            ret = read(STDIN_FILENO, buf, sizeof(buf));
            printf("read %d bytes\n", ret);

            ret = send(clientfd, buf, strlen(buf), 0);
            ERROR_CHECK(ret, -1, "send");
            printf("send %d bytes\n", ret);
        }
        if (FD_ISSET(clientfd, &readset))
        {
            memset(buf, 0, sizeof(buf));
            ret = recv(clientfd, buf, sizeof(buf), 0);
            if(ret <= 0){
                close(clientfd);
                break;
            }
            printf("recv %d bytes buf:%s\n", ret, buf);
        }
    }
    close(clientfd);
    return 0;
}
